package com.zh.common.utils

import android.os.Parcelable
import com.tencent.mmkv.MMKV

/**
 * @Author: wt
 * @Date: 2021/7/21 17:37
 * @Des: 微信MMKW存储框架
 */
object ZSpUtils {

    private val mmkv by lazy { MMKV.defaultMMKV(MMKV.MULTI_PROCESS_MODE, "") }

    /**
     * 保存各种类型
     */
    fun put(key: String, value: Any?) {
        when (value) {
            is String -> mmkv.putString(key, value)
            is Int -> mmkv.putInt(key, value)
            is Float -> mmkv.putFloat(key, value)
            is Long -> mmkv.putLong(key, value)
            is Double -> mmkv.encode(key, value)
            is Boolean -> mmkv.putBoolean(key, value)
            is ByteArray -> mmkv.putBytes(key, value)
            is Parcelable -> mmkv.encode(key, value)
        }
    }

    @JvmOverloads
    fun getString(key: String, defaultValue: String = ""): String {
        val decodeString = mmkv.decodeString(key, defaultValue)
        return if (EmptyUtils.isNotEmpty(decodeString)) decodeString.toString() else ""
    }

    @JvmOverloads
    fun getInt(key: String, defaultValue: Int = -1): Int {
        return mmkv.decodeInt(key, defaultValue)
    }

    @JvmOverloads
    fun getLong(key: String, defaultValue: Long = -1): Long {
        return mmkv.decodeLong(key, defaultValue)
    }

    @JvmOverloads
    fun getFloat(key: String, defaultValue: Float = -1F): Float {
        return mmkv.decodeFloat(key, defaultValue)
    }

    @JvmOverloads
    fun getDouble(key: String, defaultValue: Double = -1.0): Double {
        return mmkv.decodeDouble(key, defaultValue)
    }

    @JvmOverloads
    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {
        return mmkv.decodeBool(key, defaultValue)
    }

    @JvmOverloads
    fun getBytes(key: String, defaultValue: ByteArray? = null): ByteArray? {
        return mmkv.decodeBytes(key, defaultValue)
    }

    @JvmOverloads
    fun <T : Parcelable?> getParcelable(key: String, clazz: Class<T>, defaultValue: T? = null): T? {
        return mmkv.decodeParcelable(key, clazz, defaultValue)
    }

    /**
     * 保存 Set<String> 类型
     */
    fun put(key: String, value: Set<String>?) {
        mmkv.encode(key, value)
    }

    @JvmOverloads
    fun getSet(key: String, defaultValue: Set<String>? = null): Set<String>? {
        return mmkv.decodeStringSet(key, defaultValue)
    }

    /**
     * 获取保存的所有数据返回map
     */
    fun getAll(): Map<String?, *>? {
        return mmkv.all
    }

    /**
     * 是否存在key
     */
    fun contains(key: String) = mmkv.contains(key)

    /**
     * 删除
     */
    fun remove(key: String) {
        mmkv.remove(key)
    }

    /**
     * 清空
     */
    fun clear() {
        mmkv.clear()
    }
}